/**
 * 语音对话管理器
 * 整合语音识别、AI对话和语音合成功能
 */

import { doubaoChatService } from './doubaoChatService';
import { ttsService } from './ttsService';
import type { VoiceCharacter } from '../types/voiceSettings';
import { DEFAULT_VOICE_SETTINGS } from '../types/voiceSettings';
import { chatHistoryService } from './chatHistoryService';

export interface VoiceChatState {
    isListening: boolean;
    isProcessing: boolean;
    isAiThinking: boolean;
    isAiResponding: boolean;
    isSpeaking: boolean;
    userMessage: string;
    aiResponse: string;
    error: string | null;
}

export interface VoiceChatCallbacks {
    onStateChange: (state: VoiceChatState) => void;
    onUserMessage: (message: string) => void;
    onAiResponse: (response: string, isComplete: boolean) => void;
    onError: (error: string) => void;
}

class VoiceChatManager {
    private callbacks: VoiceChatCallbacks | null = null;
    private state: VoiceChatState;
    private ttsEnabled: boolean = true;
    private ttsParams: {
        vcn?: string;
        speed?: number;
        volume?: number;
        pitch?: number;
    } = {
            vcn: 'xiaoyan',
            speed: 50,
            volume: 50,
            pitch: 50
        };
    private voiceSettings = DEFAULT_VOICE_SETTINGS;

    constructor() {
        // 初始化状态，但不触发回调
        this.state = {
            isListening: false,
            isProcessing: false,
            isAiThinking: false,
            isAiResponding: false,
            isSpeaking: false,
            userMessage: '',
            aiResponse: '',
            error: null
        };

        // 初始化对话历史
        chatHistoryService.startNewSession();
    }

    /**
     * 设置回调函数
     */
    setCallbacks(callbacks: VoiceChatCallbacks): void {
        this.callbacks = callbacks;
    }

    /**
     * 设置TTS功能开关
     */
    setTtsEnabled(enabled: boolean): void {
        this.ttsEnabled = enabled;
    }

    /**
     * 设置TTS参数
     */
    setTtsParams(params: {
        vcn?: string;
        speed?: number;
        volume?: number;
        pitch?: number;
    }): void {
        this.ttsParams = { ...this.ttsParams, ...params };
        console.log('🎤 TTS参数已更新:', this.ttsParams);
    }

    /**
     * 设置语音角色
     */
    setVoiceCharacter(characterId: string): void {
        // 从DEFAULT_VOICE_SETTINGS中查找角色，确保使用最新的角色定义
        const character = DEFAULT_VOICE_SETTINGS.characters.find(c => c.id === characterId);
        if (character) {
            // 使用setTtsParams方法确保参数正确更新
            this.setTtsParams({
                vcn: character.vcn,
                speed: character.speed,
                volume: character.volume,
                pitch: character.pitch
            });
            this.voiceSettings.currentCharacter = characterId;
            console.log('🎤 语音角色已切换为:', character.name, character.description);
        } else {
            console.error('❌ 未找到语音角色:', characterId);
        }
    }

    /**
     * 获取当前语音角色
     */
    getCurrentVoiceCharacter(): VoiceCharacter | null {
        return DEFAULT_VOICE_SETTINGS.characters.find(c => c.id === this.voiceSettings.currentCharacter) || null;
    }

    /**
     * 获取所有可用的语音角色
     */
    getAvailableVoiceCharacters(): VoiceCharacter[] {
        return DEFAULT_VOICE_SETTINGS.characters;
    }

    /**
     * 测试语音播放
     */
    async testVoice(text: string = '你好，这是语音测试'): Promise<void> {
        if (!this.ttsEnabled) {
            console.log('🔇 TTS功能已禁用');
            return;
        }

        try {
            console.log('🔊 开始语音测试...');
            this.updateState({
                isSpeaking: true
            });

            await ttsService.speak(text, this.ttsParams);

            console.log('✅ 语音测试完成');
            this.updateState({
                isSpeaking: false
            });
        } catch (error) {
            console.error('❌ 语音测试失败:', error);
            this.updateState({
                isSpeaking: false
            });
        }
    }

    /**
     * 停止语音播放
     */
    stopSpeaking(): void {
        console.log('🛑 彻底停止语音播放');
        ttsService.stop();
        this.updateState({
            isSpeaking: false
        });
    }

    /**
     * 开始监听
     */
    startListening(): void {
        this.updateState({
            isListening: true,
            isProcessing: false,
            isAiThinking: false,
            isAiResponding: false,
            error: null
        });
    }

    /**
     * 停止监听
     */
    stopListening(): void {
        this.updateState({
            isListening: false
        });
    }

    /**
     * 处理语音识别结果
     */
    async handleVoiceResult(voiceText: string): Promise<void> {
        if (!voiceText || voiceText.trim() === '') {
            return;
        }

        try {
            console.log('🎤 处理语音识别结果:', voiceText);

            // 更新状态：显示用户消息
            this.updateState({
                isProcessing: false,
                isAiThinking: true,
                userMessage: voiceText,
                aiResponse: '',
                error: null
            });

            // 通知用户消息
            if (this.callbacks?.onUserMessage) {
                this.callbacks.onUserMessage(voiceText);
            }

            // 记录用户消息到对话历史
            chatHistoryService.addUserMessage(voiceText);

            // 调用豆包API获取AI回复
            console.log('🔄 开始调用豆包API...');
            const aiResponse = await doubaoChatService.sendMessage(voiceText);
            console.log('✅ 豆包API返回结果:', aiResponse);

            // 更新状态：AI回复完成
            this.updateState({
                isAiThinking: false,
                isAiResponding: false,
                aiResponse: aiResponse
            });
            console.log('📝 状态已更新，AI回复:', aiResponse);

            // 通知AI回复完成
            if (this.callbacks?.onAiResponse) {
                this.callbacks.onAiResponse(aiResponse, true);
                console.log('📢 已通知AI回复完成');
            }

            // 记录AI回复到对话历史
            const currentCharacter = this.getCurrentVoiceCharacter();
            chatHistoryService.addAiMessage(aiResponse, currentCharacter?.name);

            // 如果启用了TTS，播放AI回复的语音
            if (this.ttsEnabled && aiResponse.trim()) {
                try {
                    console.log('🔊 开始播放AI回复语音...');

                    // 彻底停止当前正在播放的语音（如果有的话）
                    console.log('🛑 停止上一个语音播放，准备播放新语音');
                    this.stopSpeaking();

                    this.updateState({
                        isSpeaking: true
                    });

                    await ttsService.speak(aiResponse, this.ttsParams);

                    console.log('✅ AI回复语音播放完成');
                    this.updateState({
                        isSpeaking: false
                    });
                } catch (ttsError) {
                    console.error('❌ TTS播放失败:', ttsError);
                    this.updateState({
                        isSpeaking: false
                    });
                    // TTS失败不影响整体流程，只记录错误
                }
            }

        } catch (error) {
            console.error('❌ 处理语音结果失败:', error);
            let errorMessage = '处理失败';

            if (error instanceof Error) {
                if (error.message.includes('429')) {
                    errorMessage = '请求过于频繁，请稍后再试';
                } else if (error.message.includes('网络')) {
                    errorMessage = '网络连接失败，请检查网络';
                } else {
                    errorMessage = error.message;
                }
            }

            this.updateState({
                isAiThinking: false,
                isAiResponding: false,
                error: errorMessage
            });

            if (this.callbacks?.onError) {
                this.callbacks.onError(errorMessage);
            }
        }
    }

    /**
     * 更新状态
     */
    private updateState(updates: Partial<VoiceChatState>): void {
        this.state = { ...this.state, ...updates };
        if (this.callbacks?.onStateChange) {
            this.callbacks.onStateChange(this.state);
        }
    }

    /**
     * 重置状态
     */
    resetState(): void {
        // 停止当前播放的语音
        ttsService.stop();

        this.state = {
            isListening: false,
            isProcessing: false,
            isAiThinking: false,
            isAiResponding: false,
            isSpeaking: false,
            userMessage: '',
            aiResponse: '',
            error: null
        };
        if (this.callbacks?.onStateChange) {
            this.callbacks.onStateChange(this.state);
        }
    }

    /**
     * 获取当前状态
     */
    getState(): VoiceChatState {
        return { ...this.state };
    }

    /**
     * 重置对话
     */
    resetConversation(): void {
        this.updateState({
            userMessage: '',
            aiResponse: '',
            error: null
        });
    }
}

// 创建全局实例
export const voiceChatManager = new VoiceChatManager();

// 导出类
export { VoiceChatManager };
export default VoiceChatManager;
